package com.momo.mal.anime;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import net.momo.mal.R;
import com.momo.mal.anime.adapter.AnimeResultAdapter;
import com.momo.mal.anime.view.AnimeView;
import com.momo.mal.database.MalDatabaseAdapter;
import com.momo.mal.entity.Anime;
import com.momo.mal.util.ConnectionUtil;
import com.momo.mal.util.DialogResult;
import com.momo.mal.util.DialogSearch;
import com.momo.mal.util.DialogSearchMangaAnime;

public class AnimeResult extends SherlockActivity {
	private ListView listAnime;
	private AnimeResultAdapter adapter;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.anime_result);
		setTitle("Anime - Result");
		
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		listAnime = (ListView) findViewById(R.id.list_anime_result);

		new RequestSearch(this).execute(getIntent().getStringExtra("query") + "");

		listAnime.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterview, View view,
					int i, long l) {
				Intent intent = new Intent(AnimeResult.this, AnimeView.class);
				intent.putExtra("anime_id", ((Anime) listAnime.getAdapter()
						.getItem(i)).getId());
				intent.putExtra("title", ((Anime) listAnime.getAdapter()
						.getItem(i)).getTitle());
				startActivity(intent);
			}
		});
		
		listAnime.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				Anime anime = ((Anime) listAnime.getAdapter()
						.getItem(position));
				new DialogResult().newInstance(anime.getId(), "anime", anime).show(getSupportFragmentManager(), null);
				
				return false;
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(getResources().getString(R.string.menu_search)).setIcon(R.drawable.ic_menu_search).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				new DialogSearchMangaAnime().newInstance().show(getSupportFragmentManager(), null);
				return false;
			}
		}).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		menu.add(getResources().getString(R.string.menu_refresh)).setIcon(R.drawable.ic_menu_refresh).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				new RequestSearch(AnimeResult.this).execute(getIntent().getStringExtra("query") + "");
				return false;
			}
		}).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if(item.getItemId() == android.R.id.home) {
			finish();
		}
		
		return super.onMenuItemSelected(featureId, item);
	}
	
	private class RequestSearch extends AsyncTask<String, Void, JSONObject> {
		private ProgressDialog mProgressDialog;
		private Context context;

		public RequestSearch(Context context) {
			mProgressDialog = new ProgressDialog(context);
			this.context = context;
		}

		@Override
		protected JSONObject doInBackground(String... params) {
			JSONObject json = null;
			try {
				json = ConnectionUtil
						.getSearch(ConnectionUtil.SECONDATY_API_HOST + "anime/search?q=" + params[0]);
			} catch (JSONException e) {
				json = null;
				e.printStackTrace();
			} catch (IOException e) {
				json = null;
				e.printStackTrace();
			}
			
			return json;
		}

		@Override
		protected void onPostExecute(JSONObject result) {
			mProgressDialog.dismiss();
			if(result == null) {
				Toast.makeText(context, getResources().getString(R.string.failed_load_data), Toast.LENGTH_LONG).show();
			} else {
				List<Anime> animes = getAnimes(result);
				if(animes.size() == 0) {
					Toast.makeText(AnimeResult.this, getResources().getString(R.string.failed_search_anime), Toast.LENGTH_LONG).show();
//					AnimeResult.this.finish();
				}
				adapter = new AnimeResultAdapter(context, animes);
				listAnime.setAdapter(adapter);
			}
		}

		@Override
		protected void onPreExecute() {
			mProgressDialog.setMessage("Data Loading ...");
			mProgressDialog.show();
		}

		private List<Anime> getAnimes(JSONObject jsonObject) {
			List<Anime> animes = new ArrayList<Anime>();
			try {
				if (jsonObject.getString("response")
						.equalsIgnoreCase("success")) {
					JSONArray jsonArray = jsonObject.getJSONArray("result");
					for (int a = 0; a < jsonArray.length(); a++) {
						JSONObject json = jsonArray.getJSONObject(a);
						Anime anime = new Anime();
						anime.setId(json.getString("id"));
						anime.setTitle(json.getString("title"));
						anime.setImageUrl(json.getString("image_url"));
						anime.setEpisode(json.getString("episodes"));
						anime.setSynopsis(json.getString("synopsis"));
						anime.setType(json.getString("type"));
						anime.setMemberScore(json.getString("members_score"));

						animes.add(anime);
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return animes;
		}
	}
}
